<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-tree :data="treeList" :props="defaultProps" :expand-on-click-node="false" ref="tree" node-key="id"
            highlight-current @node-click="handleNodeClick">
            <div slot-scope="{node, data}" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">

          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="站点名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入站点名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-row :gutter="10" class="mb8 top-right-btn small-line-height">
              <el-col :span="1.5" v-show="queryParams.bdId">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  v-hasPermi="['base:bsZd:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5" v-show="queryParams.bdId">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                  v-hasPermi="['base:bsZd:export']">导出</el-button>
              </el-col>
              <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
            </el-row>
          </el-form>
          <el-table border stripe v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
            :summary-method="getSummaries" show-summary :max-height="tableHeight">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="站点名称" align="center" prop="name" min-width="150px" show-overflow-tooltip />
            <el-table-column label="所属标段" align="center" prop="bdName" min-width="150px" show-overflow-tooltip />
            <el-table-column label="建设场景" align="center" prop="jianscj" min-width="150px" show-overflow-tooltip />
            <el-table-column label="备案容量(瓦)" header-align="center" align="right" prop="jiansrl" min-width="120px"
              show-overflow-tooltip />
            <el-table-column label="实际建设容量(瓦)" header-align="center" align="right" prop="jiansrlActual"
              min-width="130px" show-overflow-tooltip />
            <el-table-column label="单瓦造价" header-align="center" align="right" prop="danwzj" min-width="90px"
              show-overflow-tooltip />
            <el-table-column label="站点备案合同额" header-align="center" align="right" prop="zdContractAmount"
              min-width="140px" show-overflow-tooltip />
            <el-table-column label="实际合同额" header-align="center" align="right" prop="zdContractAmountActual"
              min-width="140px" show-overflow-tooltip />
            <el-table-column label="备案证名称" align="center" prop="beiazmc" min-width="150px" show-overflow-tooltip />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['base:bsZd:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['base:bsZd:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改站点对话框 -->
    <jy-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="115px">
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="所属标段" prop="bdId">
              <el-input v-model="form.bdName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入站点名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="备案容量(瓦)" prop="jiansrl">
              <!-- <el-input type="number" v-model="form.jiansrl" placeholder="请输入建设容量" /> -->
              <el-input-number class="input-number" v-model="form.jiansrl" placeholder="请输入建设容量" :precision="4"
                :controls="false" style="width: 100%;" @change="computeZdContractAmount"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单瓦造价" prop="danwzj">
              <!-- <el-input type="number" v-model="form.danwzj" placeholder="请输入单瓦造价" /> -->
              <el-input-number class="input-number" v-model="form.danwzj" placeholder="请输入单瓦造价" :precision="4"
                :controls="false" style="width: 100%;" @change="computeZdContractAmount"></el-input-number>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="实际建设容量(瓦)" prop="jiansrlActual">
              <el-input-number class="input-number" v-model="form.jiansrlActual" placeholder="请输入建设容量" :precision="4"
                :controls="false" style="width: 100%;" @change="computeZdContractAmount"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变动后价格" prop="chgPrice">
              <el-input-number class="input-number" v-model="form.chgPrice" placeholder="请输入变动价格" :precision="4"
                :controls="false" style="width: 100%;" @change="computeZdContractAmount">
              </el-input-number>
            </el-form-item>
            <!--            <el-form-item label="变动价格" prop="chgPrice">-->
            <!--              <el-input v-model="form.chgPrice" placeholder="请输入" />-->
            <!--            </el-form-item>-->
          </el-col>
        </el-row>

        <el-row :gutter="8">
          <el-col :span="12">
            <el-form-item label="站点备案合同额" prop="zdContractAmount">
              <el-input v-model="form.zdContractAmount" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际合同额" prop="zdContractAmountActual">
              <el-input v-model="form.zdContractAmountActual" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="8">
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="24">
            <el-form-item label="建设场景" prop="jianscj">
              <el-input v-model="form.jianscj" placeholder="请输入建设场景" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备案证名称" prop="beiazmc">
              <el-input type="textarea" v-model="form.beiazmc" placeholder="请输入备案证名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input type="textarea" v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="8">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </jy-dialog>
  </div>
</template>

<script>
import { queryBdSelect } from "@/api/base/bsBd";
import { listBsZd, getBsZd, delBsZd, addBsZd, updateBsZd } from "@/api/base/bsZd";
import { mapGetters } from "vuex";
import decimal from "@/utils/big-decimal";

export default {
  name: "BsZd",
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 站点表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
        name: undefined,
        sort: undefined,
        jianscj: undefined,
        jiansrl: undefined,
        danwzj: undefined,
        beiazmc: undefined,
        bdName: undefined
      },
      projectId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        bdId: [
          { required: true, message: "所属标段id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "站点名称不能为空", trigger: "blur" }
        ],
        jianscj: [
          { required: true, message: "建设场景不能为空", trigger: "blur" }
        ],
        jiansrl: [
          { required: true, message: "建设容量不能为空", trigger: "blur" }
        ],
        danwzj: [
          { required: true, message: "单瓦造价不能为空", trigger: "blur" }
        ],
        beiazmc: [
          { required: true, message: "备案证名称不能为空", trigger: "blur" }
        ],
        bdName: [
          { required: true, message: "所属标段名称不能为空", trigger: "blur" }
        ]
      },
      tableHeight: document.documentElement.scrollHeight - 220,
    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      this.changeProject(newVal);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.projectChangeResetQuery();
      // 系统顶部选中项目变化
      this.getBdList();
    },
    getBdList () {
      queryBdSelect({ projectId: this.projectId }).then(response => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            this.$refs.tree.setCurrentKey(this.treeList[0].id);
            this.handleNodeClick(this.treeList[0]);
          }
        });
      });
    },
    handleNodeClick (data) {
      this.queryParams.bdId = data.id;
      this.treeInfo = data;
      this.handleQuery();
    },
    projectChangeResetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        qsId: undefined,
        bdId: undefined,
      };
      this.total = 0;
      this.dataList = [];
    },
    /** 查询站点列表 */
    getList () {
      this.loading = true;
      listBsZd(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        bdId: this.treeInfo.id,
        name: undefined,
        remark: undefined,
        address: undefined,
        sort: undefined,
        jianscj: undefined,
        jiansrl: undefined,
        danwzj: undefined,
        beiazmc: undefined,
        bdName: this.treeInfo.name,
        zdContractAmount: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加站点";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getBsZd(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改站点";
      });
    },
    // 计算站点备案合同额，实际合同额
    computeZdContractAmount () {
      let a = this.form.jiansrl; //建设容量,备案容量
      let b = this.form.danwzj; //单瓦造价
      let c = this.form.jiansrlActual; //实际建设容量
      let d = this.form.chgPrice; //变动后价格
      this.form.zdContractAmount = decimal.multiply(a, b, 2);
      this.form.zdContractAmountActual = decimal.multiply(c, b, 2);
      if (d) {
        // this.form.zdContractAmount = decimal.multiply(a, d, 2);
        this.form.zdContractAmountActual = decimal.multiply(c, d, 2);
      }
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateBsZd(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBsZd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除站点名称为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        return delBsZd(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    // 拼接合计
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 4 || index === 5 || index === 6 || index === 7 || index === 8) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return decimal.add(prev, curr, 2);
              } else {
                return decimal.round(prev);
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('base/bsZd/export', {
        ...this.queryParams
      }, `bsZd_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>
<style lang="scss" scoped>
.input-number {
  ::v-deep .el-input__inner {
    text-align: left;
  }
}
</style>
